<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

require '../config.php';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo "<p class='error'>无效的帖子ID</p>";
    exit();
}

$post_id = $_GET['id'];
$user_id = $_SESSION['user_id'];

// 获取帖子详情
$stmt = $conn->prepare("SELECT title, content, created_at, media, user_id FROM posts WHERE id = ?");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($post_title, $post_content, $post_created_at, $post_media, $post_user_id);
$stmt->fetch();

// 检查帖子是否存在
if ($stmt->num_rows == 0) {
    echo "<p class='error'>帖子不存在</p>";
    exit();
}

// 获取评论
$comment_stmt = $conn->prepare("SELECT c.id, c.content, c.created_at, u.username FROM comments c JOIN users u ON c.user_id = u.id WHERE c.post_id = ? AND c.parent_id IS NULL ORDER BY c.created_at ASC");
$comment_stmt->bind_param("i", $post_id);
$comment_stmt->execute();
$comment_stmt->store_result();
$comment_stmt->bind_result($comment_id, $comment_content, $comment_created_at, $comment_username);

// 处理AJAX请求
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    $action = $_POST['action'];
    $response = [];

    if ($action == 'submit_comment') {
        $comment = $_POST['comment'];
        $user_id = $_SESSION['user_id'];

        $stmt = $conn->prepare("INSERT INTO comments (post_id, user_id, content) VALUES (?, ?, ?)");
        $stmt->bind_param("iis", $post_id, $user_id, $comment);

        if ($stmt->execute()) {
            // 发送评论通知
            $notification_content = "您的帖子收到了新的评论: " . htmlspecialchars($comment);
            $notification_stmt = $conn->prepare("INSERT INTO notifications (user_id, type, content) VALUES (?, 'comment', ?)");
            $notification_stmt->bind_param("is", $post_user_id, $notification_content);
            $notification_stmt->execute();
            $notification_stmt->close();

            $response['status'] = 'success';
            $response['message'] = '评论成功';
        } else {
            $response['status'] = 'error';
            $response['message'] = '发表评论失败，请重试';
        }

        $stmt->close();
    } elseif ($action == 'reply_comment') {
        $parent_id = $_POST['parent_id'];
        $reply_content = $_POST['reply_content'];

        // 获取被回复评论的用户ID
        $parent_user_stmt = $conn->prepare("SELECT user_id FROM comments WHERE id = ?");
        $parent_user_stmt->bind_param("i", $parent_id);
        $parent_user_stmt->execute();
        $parent_user_stmt->bind_result($parent_user_id);
        $parent_user_stmt->fetch();
        $parent_user_stmt->close();

        $reply_stmt = $conn->prepare("INSERT INTO comments (post_id, user_id, content, parent_id) VALUES (?, ?, ?, ?)");
        $reply_stmt->bind_param("iisi", $post_id, $user_id, $reply_content, $parent_id);
        $reply_stmt->execute();
        $reply_stmt->close();

        // 发送回复通知
        $notification_content = "您的评论收到了新的回复: " . htmlspecialchars($reply_content);
        $notification_stmt = $conn->prepare("INSERT INTO notifications (user_id, type, content) VALUES (?, 'reply', ?)");
        $notification_stmt->bind_param("is", $parent_user_id, $notification_content);
        $notification_stmt->execute();
        $notification_stmt->close();

        $response['status'] = 'success';
        $response['message'] = '回复成功';
    }

    echo json_encode($response);
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($post_title ?? '帖子详情'); ?> - 论坛</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            background-image: url('https://images.unsplash.com/photo-1506748686214-e9df14d4d9d0');
            background-size: cover;
            background-position: center;
            color: #4c4948;
            font-family: 'Lato', Arial, sans-serif;
            margin: 0;
            display: flex;
            min-height: 100vh;
        }
        .overlay {
            background: rgba(255, 255, 255, 0.8);
            width: 100%;
            display: flex;
        }
        .sidebar {
            background-color: #2d3748;
            color: white;
            width: 250px;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            border-radius: 15px;
            margin: 20px;
        }
        .sidebar a {
            color: white;
            display: block;
            padding: 10px 20px;
            margin: 10px 0;
            background: #3b4252;
            border-radius: 25px;
            transition: background 0.3s;
        }
        .sidebar a:hover {
            background: #a0aec0;
        }
        .main-content {
            flex: 1;
            padding: 20px;
            display: flex;
            flex-direction: column;
            margin: 20px;
            border-radius: 15px;
            background: #fff;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .bg-header {
            background-image: url('https://images.unsplash.com/photo-1542281286-9e0a16bb7366');
            background-size: cover;
            background-position: center;
            height: 200px;
            border-radius: 15px;
            position: relative;
            overflow: hidden;
        }
        .bg-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 0;
        }
        .bg-header h2 {
            position: relative;
            z-index: 1;
            color: white;
            text-align: center;
            line-height: 200px;
            font-size: 2rem;
            margin: 0;
        }
        .card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }
        .media-content img,
        .media-content video,
        .media-content audio {
            max-width: 100%;
            height: auto;
        }
        .comment-list li {
            padding: 20px;
            border-bottom: 1px solid #e2e8f0;
            position: relative;
        }
        .reply-form {
            display: flex;
            align-items: center;
            position: absolute;
            right: 0;
            top: 0;
            background: rgba(255, 255, 255, 0.8);
            padding: 10px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .reply-form textarea {
            width: 200px;
            background: rgba(255, 255, 255, 0.8);
            border: 1px solid #ccc;
            padding: 5px;
            border-radius: 5px;
            resize: none;
            margin-right: 10px;
        }
        .reply-form button {
            background: #1a73e8;
            color: white;
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s;
        }
        .reply-form button:hover {
            background: #0c4ea2;
        }
    </style>
</head>
<body>
    <div class="overlay">
        <div class="sidebar">
            <h2 class="text-3xl font-bold mb-8">帖子详情</h2>
            <nav class="w-full">
                <a href="../feed.php" class="text-lg">帖子</a>
                <a href="create_post.php" class="text-lg">发布新帖子</a>
                <a href="notifications.php" class="text-lg">通知</a>
                <a href="../logout.php" class="text-lg text-red-500 hover:text-red-700">退出登录</a>
            </nav>
        </div>
        <div class="main-content">
            <div class="bg-header">
                <h2><?php echo htmlspecialchars($post_title ?? '帖子详情'); ?></h2>
            </div>
            <div class="card">
                <p class="text-lg mb-4"><?php echo htmlspecialchars($post_content ?? ''); ?></p>
                <p class="text-sm text-gray-500 mb-4">发布时间: <?php echo $post_created_at; ?></p>
                <?php if (!empty($post_media)): ?>
                    <div class="media-content mb-4">
                        <?php
                        $media_type = mime_content_type('../' . $post_media);
                        if (strpos($media_type, 'image') !== false) {
                            echo "<img src='../$post_media' alt='图片'>";
                        } elseif (strpos($media_type, 'video') !== false) {
                            echo "<video controls>
                                    <source src='../$post_media' type='$media_type'>
                                  </video>";
                        } elseif (strpos($media_type, 'audio') !== false) {
                            echo "<audio controls>
                                    <source src='../$post_media' type='$media_type'>
                                  </audio>";
                        }
                        ?>
                    </div>
                <?php endif; ?>
                <h3 class="text-xl font-bold mb-4">评论</h3>
                <ul id="comment-list" class="comment-list space-y-4">
                    <?php
                    if ($comment_stmt->num_rows > 0) {
                        while ($comment_stmt->fetch()) {
                            echo "<li><strong>" . htmlspecialchars($comment_username) . ":</strong> " . htmlspecialchars($comment_content) . " - " . $comment_created_at;
                            echo "<form class='reply-form' data-comment-id='$comment_id'>
                                    <textarea name='reply_content' required></textarea>
                                    <button type='submit'>回复</button>
                                  </form>";
                            // 获取回复
                            $reply_stmt = $conn->prepare("SELECT c.content, c.created_at, u.username FROM comments c JOIN users u ON c.user_id = u.id WHERE c.parent_id = ? ORDER BY c.created_at ASC");
                            $reply_stmt->bind_param("i", $comment_id);
                            $reply_stmt->execute();
                            $reply_stmt->store_result();
                            $reply_stmt->bind_result($reply_content, $reply_created_at, $reply_username);

                            if ($reply_stmt->num_rows > 0) {
                                echo "<ul class='ml-4'>";
                                while ($reply_stmt->fetch()) {
                                    echo "<li><strong>" . htmlspecialchars($reply_username) . ":</strong> " . htmlspecialchars($reply_content) . " - " . $reply_created_at . "</li>";
                                }
                                echo "</ul>";
                            }
                            $reply_stmt->close();
                            echo "</li>";
                        }
                    } else {
                        echo "<li>暂无评论</li>";
                    }
                    ?>
                </ul>
                <h3 class="text-xl font-bold mt-8 mb-4">发表评论</h3>
                <form id="comment-form" class="space-y-4">
                    <div class="form-group">
                        <label for="comment" class="block text-gray-700">评论:</label>
                        <textarea id="comment" name="comment" class="w-full border border-gray-300 p-2 rounded-md" required></textarea>
                    </div>
                    <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-700">发表评论</button>
                </form>
                <a href="index.php" class="mt-4 inline-block text-blue-500">返回主页</a>
            </div>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        $('#comment-form').on('submit', function(e) {
            e.preventDefault();
            var comment = $('#comment').val();

            $.ajax({
                url: 'view_post.php?id=<?php echo $post_id; ?>',
                type: 'POST',
                data: {
                    action: 'submit_comment',
                    comment: comment
                },
                success: function(response) {
                    var data = JSON.parse(response);
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert(data.message);
                    }
                }
            });
        });

        $('.reply-form').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var parent_id = form.data('comment-id');
            var reply_content = form.find('textarea[name="reply_content"]').val();

            $.ajax({
                url: 'view_post.php?id=<?php echo $post_id; ?>',
                type: 'POST',
                data: {
                    action: 'reply_comment',
                    parent_id: parent_id,
                    reply_content: reply_content
                },
                success: function(response) {
                    var data = JSON.parse(response);
                    if (data.status === 'success') {
                        location.reload();
                    } else {
                        alert(data.message);
                    }
                }
            });
        });
    });
    </script>
</body>
</html>